package sandbox;

import helpers.d;
import soenudp.Command;
import soenudp.UDPHelper;
import soenudp.UDPMessage;
import soenudp.UDPException;

public class Unicast2Unicast extends Thread
{
  final static int    GMS_PORT = 20000; 
  final static String MTL_MULTICAST_ADR   = "235.255.0.1";
  final static int    MTL_MULTICAST_PORT  = 9200;
    
  UDPHelper socketHelper;
  UDPHelper groupHelper; //Used to Shutdown (leave group). 
  Thread parent;
  public Unicast2Unicast(UDPHelper socketHelper, UDPHelper groupHelper, Thread  parent) 
  {
    this.socketHelper = socketHelper;
    this.groupHelper = groupHelper;
    this.parent = parent;
  }

  @SuppressWarnings("unused")
  public void run()
  {
    try 
    {  
      UDPMessage request;  
      boolean exit = false;;
      while ( (request = socketHelper.getMessage()) != null)
      {
        int       fromPort  = request.recv_from_port;
        String    fromIP    = request.recv_from_ip.replaceFirst("/", "");
        String    optioText = request.op_text; //in case you need more...
        Command   command   = request.command;
        long      trasnsc   = request.transac;
        switch(command)
        {
          case SHUTDOWN:             
            groupHelper.leaveGroup();
            socketHelper.stopUnicast();
            groupHelper = null;
            exit = true;
            parent.interrupt(); // For the other Blocking Queue
            break;
           
         
          case BPING:
              
              UDPMessage response = new UDPMessage();
              response.command = Command.PONG;     
              response.op_text = "HARDCODE";//This is the NodeID, you have it a the top of DTRSManger...
              socketHelper.sendToNode(fromIP, GMS_PORT, response); //Reply back.
              break;   
          default:
            System.out.println("Received " + command +  " From IP: " + fromIP + 
              " PORT: " + fromPort + " Transaction id: " + trasnsc);
            break;
        }
        if (exit) break;
      }
      
      //d.listAllThreads();
    } 
    catch (UDPException e) 
    {
      e.printStackTrace();
    }
    d.out("Good-bye");
    this.interrupt();
    
  }
  
}
